package m.store.action;

import m.base.action.StoreInfoAction;
import m.base.util.PowerUtil;
import m.common.action.ActionMeta;
import m.common.action.RequestMeta;
import m.common.action.VueResult;
import m.common.model.util.*;
import m.html.VueFormResult;
import m.html.VueListResult;
import m.html.element.Element;
import m.html.element.attr.Align;
import m.html.element.attr.ButtonType;
import m.html.form.*;
import m.html.list.EventType;
import m.html.list.ListButton;
import m.html.list.ListEvent;
import m.html.list.SuccessMethod;
import m.store.model.*;
import m.store.service.VirtualStockService;
import m.system.exception.MException;
import m.system.util.JSONMessage;
import m.system.util.ObjectUtil;
import manage.model.StatusModel;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

@ActionMeta(name = "store/virtualStock")
public class VirtualStockAction extends OrderModelAction{
    private StockInfo model;
    private List<StoreGoods> goodsList;
    @RequestMeta(logTitle = "虚拟库存",logDescription = "商户添加虚拟商品库存",transaction = true)
    public JSONMessage doAddVirtualStock() throws Exception {
        if(null==model|| ObjectUtil.isEmptyOid(model.getGuest())) throw new MException(this.getClass(),"请选择可调货客户信息");
        if(null==goodsList||goodsList.isEmpty()) throw new MException(this.getClass(),"请选择可调商品信息");
        getService(VirtualStockService.class).addVirtualStock(model.getGuest().getOid(),goodsList);
        return new JSONMessage(0,"添加成功");
    }
    @RequestMeta(logTitle = "虚拟库存",logDescription = "商户删除虚拟商品库存",params = {"oid"})
    public JSONMessage doDelete(String oid) throws Exception {
        GoodsStockRecord record=ModelQueryList.getModel(GoodsStockRecord.class,oid,"*","stock.type");
        if(null==record) throw new MException(this.getClass(),"没有找到数据");
        if(!StockInfo.Type_Virtual.equals(record.getStock().getType())) throw new MException(this.getClass(),"数据错误");
        if(!ModelQueryList.getModelList(GoodsOutRecord.class,new String[]{"oid"},new QueryPage(0,1),QueryCondition.eq("record.oid",oid)).isEmpty()){
            throw new MException(this.getClass(),"已被关联待出库，不能删除。");
        }
        ModelUpdateUtil.deleteModel(record);
        return new JSONMessage(0,"删除成功");
    }
    @RequestMeta(logTitle = "虚拟库存",logDescription = "商户删除客户所有的虚拟商品库存",params = {"guestOid"})
    public JSONMessage doDeleteGuest(String guestOid) throws SQLException, MException {
        List<GoodsStockRecord> ls=ModelQueryList.getModelList(GoodsStockRecord.class,new String[]{"oid"},null,
            QueryCondition.and(
                QueryCondition.eq("stock.guest.oid",guestOid),
                QueryCondition.eq("stock.type",StockInfo.Type_Virtual)
            )
        );
        int success=0;
        for(GoodsStockRecord r : ls){
            try {
                doDelete(r.getOid());
                success++;
            } catch (Exception ignored) {
            }
        }
        return new JSONMessage(0,"成功删除了"+success+"项");
    }
    public VueResult toAdd() throws Exception {
        model=new StockInfo();
        model.setGuest(new GuestInfo());
        ModelForm form = new ModelForm("批量添加虚拟库存");
        form.addItem(
            FormInput.selectOneModel("可调货客户", "model","guest","'action/store/guestInfo/selectOneGuest'",1300,"<a @click=\"viewGuest\">{{model.guest.name}}</a>").setSpan(3),
            FormInput.selectManyModel("可调商品","list","goodsList","'"+actionUrl("selectStoreGoods")+"?params[guestOid]='+model.guest.oid", Element.tag("div").A("v-for","item in list.goodsList").E("{{item.name}}").toString()).setSpan(3)
        )
        .addData("model",model)
        .addData("list",new JSONMessage().push("goodsList",new ArrayList<>()))
        .addButton(
            FormButton.pri("确定添加","doAddVirtualStock")
        )
        .addMethod(
            FormEvent.backFlag,
            FormEvent.doJson("doAddVirtualStock",actionUrl("doAddVirtualStock"),"{model:this.model,goodsList:this.list.goodsList}")
                .success("backFlag")
        );
        VueFormResult result=new VueFormResult();
        return result.addForm(form)
            .addForm(new CustomForm(Element.tag("a-alert").A("message","请先选择客户信息后再选择商品信息。")));
    }
    public VueResult selectStoreGoods() throws Exception {
        String selected=getParamsValue("selected","");
        String guestOid=getParamsValue("guestOid","");
        VueListResult result=getVueListResult("选择商品",StoreGoods.class,actionUrl("selectStoreGoods"));
        result.setDescribe("<a-alert :message=\"'已选择'+sumSelected(item=>1)+'种商品。'\" style=\"margin-bottom:10px;\" />");
        result.setSelection("oid", false);
        result.addCol(toIndexColumn());
        result.addCol(toTextColumn("商品类型", "typeName", 100, true));
        result.addCol(toTextColumn("厂商", "factoryName", 100, true));
        result.addCol(toLinkColumn("名称", "name", 250, true,
            new ListEvent(actionUrl(StoreInfoAction.class,"toView"), EventType.MODAL,600)
                .addParam("model.oid","oid")
        ));
        result.addCol(toTextColumn("商品分类", "storeType.oid", 100, true).setDictType(StoreType.class, PowerUtil.getSessionStoreOid()));
        result.addCol(toNumberColumn("报价","offerPrice",100,true));
        result.addButton(ListButton.back("选择", ButtonType.PRIMARY).addParam("",""));
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("store.oid",PowerUtil.getSessionStoreOid()));
        result.addCondition(QueryCondition.eq("status", StatusModel.Status_Enable));
        result.addCondition(QueryCondition.eq("property",StoreGoods.Property_Goods));
        result.addCondition(QueryCondition.not(
            QueryCondition.in("oid",
                ModelQueryList.instance(GoodsStockRecord.class,new String[]{"goods.oid"},null,
                    QueryCondition.and(
                        QueryCondition.eq("stock.type",StockInfo.Type_Virtual),
                        QueryCondition.eq("stock.guest.oid",guestOid)
                    )
                )
            )
        ));
        return result;
    }
    /*
     * 虚拟库存列表
     */
    public VueResult allList() throws Exception {
        VueListResult result=getVueListResult("虚拟库存", GoodsStockRecord.class,actionUrl("allList"));
        result.setSubTitle("可无货出库，选择虚拟库存出库会自动生成调拨入库。");
        result.setMergeCellsInfo(1,2);
        result.setSelection("oid",false);
        result.setLineClamp(3);
        result.addCol(toIndexColumn());
        result.addCol(toTextColumn("可调货客户", "stock.guest.name", 150, true));
        result.addCol(toTextColumn("操作人", "stock.inputUser.realname", 100, true));
        result.addCol(toTextColumn("可调商品", "goods.name", 400, true));
        result.addCol(toDateTimeColumn("操作时间","operDate",130,true));
        result.addCol(toSpaceColumn("操作", 100,
            ListButton.ajax("删除", ButtonType.WARN,actionUrl("doDelete"), SuccessMethod.REFRESH)
                .addParam("oid","oid").setConfirm("确定要删除吗？")
        ).setFixed(Align.RIGHT));
        result.addButton(
            ListButton.modal("批量新增", ButtonType.PRIMARY,actionUrl("toAdd"),500, SuccessMethod.REFRESH),
            ListButton.ajax("删除", ButtonType.WARN,actionUrl("doDelete"), SuccessMethod.REFRESH)
                    .addParam("oid","oid").setConfirm("确定要删除吗？")
        );
        //排序 result.addOrder
        //查询条件 result.addCondition
        result.addCondition(QueryCondition.eq("store.oid",PowerUtil.getSessionStoreOid()));
        result.addCondition(QueryCondition.eq("stock.type",StockInfo.Type_Virtual));
        result.addOrder(
            QueryOrder.asc("stock.guest.name"),
            QueryOrder.asc("goods.name")
        );
        return result;
    }
    public StockInfo getModel() {
        return model;
    }

    public void setModel(StockInfo model) {
        this.model = model;
    }

    public List<StoreGoods> getGoodsList() {
        return goodsList;
    }

    public void setGoodsList(List<StoreGoods> goodsList) {
        this.goodsList = goodsList;
    }
}
